﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace RFPL
{
    public partial class NewSeason : Form
    {
        public int seasonId = 0;

        public NewSeason()
        {
            InitializeComponent();
        }

        private void save_Click(object sender, EventArgs e)
        {            
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = Global.connectionString;
            SqlCommand myCommand = conn.CreateCommand();
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.CommandText = "[addSeason]";
            myCommand.Parameters.Add("@name", SqlDbType.NVarChar, tbSeasonName.Text.Length).Value = Convert.ToString(tbSeasonName.Text);
                   
            conn.Open();
            seasonId = Convert.ToInt32(myCommand.ExecuteScalar());
            conn.Close();

            if (seasonId != 0) { 
            
                conn = new SqlConnection();
                conn.ConnectionString = Global.connectionString;
                conn.Open();

                List<int> comands = new List<int>();
                int clubId = 0;

                List<int> compIds = new List<int>();

                foreach (DataGridViewRow row in dgvClubs.Rows)
                {
                    if (Convert.ToBoolean(row.Cells["competitor"].Value))
                    {
                        clubId = Convert.ToInt32(row.Cells["id"].Value);
                        comands.Add(clubId);

                        myCommand = conn.CreateCommand();
                        myCommand.CommandType = CommandType.StoredProcedure;
                        myCommand.CommandText = "[addCompetitors]";
                        myCommand.Parameters.Add("@seasId", SqlDbType.Int).Value = seasonId;
                        myCommand.Parameters.Add("@clubId", SqlDbType.Int).Value = clubId;
                       
                        myCommand.ExecuteScalar();

                        compIds.Add(Convert.ToInt32(row.Cells["id"].Value));

                    }
                }

                if (compIds.Count%2 !=0){       // чтоб игроков было чётн кол-во
                    compIds.Add(0); // если не чётное - добавляем 0 в конец
                }

                int tourId = 0;
                int compCnt = compIds.Count;    // всего участников
                int tourCount = (compCnt - 1)*2; // кол-во туров в сезоне
                int gameCount = compCnt/2; // кол-во игр в туре

                for (int tourNum = 0; tourNum < tourCount; tourNum++)
                {

                    myCommand = conn.CreateCommand();
                    myCommand.CommandType = CommandType.StoredProcedure;
                    myCommand.CommandText = "[addTour]";
                    myCommand.Parameters.Add("@fk_session", SqlDbType.Int).Value = seasonId;
                    myCommand.Parameters.Add("@num", SqlDbType.Int).Value = tourNum;
                       
                    tourId = Convert.ToInt32(myCommand.ExecuteScalar());

                    for (int gameNum = 0;gameNum<gameCount;gameNum++){
                    
                        myCommand = conn.CreateCommand();
                        myCommand.CommandType = CommandType.StoredProcedure;
                        myCommand.CommandText = "[addGame]";
                        //fk_tour,fk_club1,fk_club2,date,fk_stadion
                        myCommand.Parameters.Add("@fk_tour", SqlDbType.Int).Value = tourId;

                        if (compIds[gameNum] != 0)
                            myCommand.Parameters.Add("@fk_club1", SqlDbType.Int).Value = compIds[gameNum];
                        else
                            myCommand.Parameters.Add("@fk_club1", SqlDbType.Int).Value = DBNull.Value;

                        if (compIds[compCnt-gameNum-1] != 0)
                            myCommand.Parameters.Add("@fk_club2", SqlDbType.Int).Value = compIds[compCnt-gameNum-1];
                        else
                            myCommand.Parameters.Add("@fk_club2", SqlDbType.Int).Value = DBNull.Value;

                        if (tourNum < tourCount/2 ){ // в зависимости от дивизиона
                        
                            if ((compIds[gameNum] != 0)&&(compIds[compCnt-gameNum-1] != 0)){ // если играют две команды                            
                                 myCommand.Parameters.Add("@fk_stadion", SqlDbType.Int).Value = getClubStadionId(compIds[gameNum]);     // игра проходит дома
                            }
                            else{                            
                                 myCommand.Parameters.Add("@fk_stadion", SqlDbType.Int).Value = DBNull.Value;                               
                            }

                        }else{
                        
                            if ((compIds[gameNum] != 0)&&(compIds[compCnt-gameNum-1] != 0)){ // если играют две команды                            
                                 myCommand.Parameters.Add("@fk_stadion", SqlDbType.Int).Value = getClubStadionId(compIds[compCnt-gameNum-1]);     // или в гостях 
                            }
                            else{                            
                                 myCommand.Parameters.Add("@fk_stadion", SqlDbType.Int).Value = DBNull.Value;                             
                            }
                        }

                        myCommand.ExecuteScalar();

                    }

                    makeCirkle(compIds);
                    
                }

                conn.Close();

            }

            this.Close();
        }

        private void makeCirkle(List<int> comp) {
            int el = comp[1];
            comp.RemoveAt(1);
            comp.Add(el);        
        }

        private int getClubStadionId(int clubId)
        {
            int res = 0;

            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = Global.connectionString;
            SqlCommand myCommand = conn.CreateCommand();
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.CommandText = "[getClubStadionId]";
            myCommand.Parameters.Add("@id", SqlDbType.Int).Value = clubId;

            conn.Open();
            res = Convert.ToInt32(myCommand.ExecuteScalar());
            conn.Close();

            return res;
            
        }

        private void NewSeason_Load(object sender, EventArgs e)
        {
            UpdateClubList();
        }

        private void UpdateClubList()
        {
            SqlDataReader dataReader = Global.getDataReader("[getAllClubsPreview]");
            while (dataReader.Read())
            {
                dgvClubs.Rows.Add(dataReader["id"],false, dataReader["label"], dataReader["name"]);

            }
            dataReader.Close();
            Global.closeConnection();
        }

        private void tbSeasonName_TextChanged(object sender, EventArgs e)
        {
            setSaveState();
        }

        private void dgvSeasons_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            setSaveState();
        }

        private void setSaveState() {

            int compCnt = 0;

            foreach (DataGridViewRow row in dgvClubs.Rows)
            {
                DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells["competitor"];
                if (Convert.ToBoolean(cell.Value))
                {
                    compCnt++;
                }
            }

            if (compCnt > 1 && tbSeasonName.Text.Length > 0)
            {
                save.Enabled = true;
            }
            else
            {
                save.Enabled = false;
            }

        }

        private void dgvClubs_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            setSaveState();
        }

        private void dgvClubs_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            dgvClubs.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
        
    }
}
